#include"Slist.h"
struct SListNode;
typedef struct SListNode SLTNode;

void SLTPrint(SLTNode* phead)
{
	while (phead)
	{
		printf("%d->", phead->a);
		phead=phead->next;
	}
	printf("NULL\n");
}

SLTNode* SLTBuyNode(SLTDataType x)
{
	SLTNode* newnode = (SLTNode*)malloc(sizeof(SLTNode));
	if (newnode==NULL)
	{
		perror("malloc fail!");
		exit(1);
	}
	newnode->a = x;
	newnode->next = NULL;
	return newnode;
}

void SLTPushBack(SLTNode** pphead, SLTDataType x)
{
	SLTNode* newnode = SLTBuyNode(x);
	if (*pphead==NULL)
	{
		*pphead = newnode;
	}
	else
	{
		SLTNode* prev = *pphead;
		while (prev->next)
		{
			prev = prev->next;
		}
		prev->next = newnode;
	}
}

void SLTPushFront(SLTNode** pphead, SLTDataType x)
{
	assert(pphead);
	SLTNode* newnode = SLTBuyNode(x);
	newnode->next = *pphead;
	*pphead = newnode;
}

void SLTPopBack(SLTNode** pphead)
{
	assert(pphead&&*pphead);
	if ((*pphead)->next==NULL)
	{
		free(*pphead);
		*pphead = NULL;
	}
	else
	{
		SLTNode* plast = *pphead;
		SLTNode* plist = *pphead;
		while (plist->next)
		{
			plast = plist;
			plist = plist->next;
		}
		free(plast->next);
		plast->next = NULL;
	}
}

void SLTPopFront(SLTNode** pphead)
{
	assert(pphead && *pphead);
	SLTNode* prev = *pphead;
	prev = prev->next;
	free(*pphead);
	*pphead = prev;
}

SLTNode* SLTFind(SLTNode* phead, SLTDataType x)
{
	while (phead)
	{
		if (phead->a == x)
		{
			return phead;
		}
		phead = phead->next;
	}
	return NULL;
}

void SLTInsert(SLTNode** pphead, SLTNode* pos, SLTDataType x)
{
	assert(pphead && *pphead);
	assert(pos);
	if (*pphead == pos)
	{
		SLTPushFront(pphead, x);
	}
	else
	{
		SLTNode* phead = SLTBuyNode(x);
		SLTNode* prev = *pphead;
		while (prev->next!=pos)
		{
			prev = prev->next;
		}
		phead->next = pos;
		prev->next = phead;
	}
}

void SLTErase(SLTNode** pphead, SLTNode* pos)
{
	assert(pphead && *pphead);
	assert(pos);
	SLTNode* prev = *pphead;
	SLTNode* stp = *pphead;
	if (pos == *pphead)
	{
		SLTPopFront(pphead);
	}
	else
	{
		while (prev->next != pos)
		{
			stp = prev;
			prev = prev->next;
		}
		stp->next = prev->next;
		free(prev);
		prev = NULL;
	}
}

void SLTInsertAfter(SLTNode* pos, SLTDataType x)
{
	assert(pos);
	SLTNode* newnode = SLTBuyNode(x);
	newnode->next = pos->next;
	pos->next = newnode;
}

void SLTEraseAfter(SLTNode* pos)
{
	assert(pos&&pos->next);
	SLTNode* prev = pos->next;
	pos->next = prev->next;
	free(prev);
	prev = NULL;
}

void SListDesTroy(SLTNode** pphead)
{
	assert(pphead && *pphead);
	SLTNode* prev = *pphead;
	while (prev)
	{
		SLTNode* next = prev->next;
		free(prev);
		prev = next;
	}
	*pphead = NULL;
}